package com.example.sqliteapplication;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sqliteapplication.service.QueryAddressService;
import com.example.sqliteapplication.utils.AddressDBUtils;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import pub.devrel.easypermissions.EasyPermissions;


public class AddressActivity extends AppCompatActivity {

    private Button btnSearch;
    private TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        //getDatabase();
        String[]perms={Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE};
        if(!EasyPermissions.hasPermissions(this,perms)){
           EasyPermissions.requestPermissions(this,"",1,perms);
        }

        getDBFromAssets();
        CheckBox checkBox= (CheckBox) findViewById(R.id.cb_start);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    //kaiqi
                    Intent intent=new Intent(getApplicationContext(), QueryAddressService.class);
                    startService(intent);

                }else{
                    //close
                    Intent intent=new Intent(getApplicationContext(), QueryAddressService.class);
                    stopService(intent);
                }
            }
        });
        btnSearch = (Button) findViewById(R.id.btn_s);
        tvResult = (TextView) findViewById(R.id.tv_result);
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String address=AddressDBUtils.findaddress(getApplicationContext(),"110");
                tvResult.setText(address);
            }
        });
        //listenIncomingCall();


    }

    private void listenIncomingCall() {
        TelephonyManager tm= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }

    private void getDBFromAssets() {
        try {
            InputStream in  = getAssets().open("address.db");
            FileOutputStream out=new FileOutputStream(new File(getFilesDir(),"address.db"));
            byte[]buf=new byte[1024];
            int len=0;
            while((len=in.read(buf))!=-1){
                out.write(buf,0,len);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void searchAll() {
//        Cursor cursor=AddressDBUtils.findall(getApplicationContext());
//        Log.i("Main","search ok"+cursor.getCount());
//        cursor.moveToFirst();
//        Log.i("Main", cursor.getString(1)+"/"+cursor.getString(4));

    }

    private void getDatabase() {
        //从服务器获取db，保存在data/data/报名/files/address.db
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder().url("http://10.0.2.2:8080/address.db").build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                Log.i("Main", "onResponse:ok ");
                InputStream in = response.body().byteStream();
                OutputStream out=new FileOutputStream(new File(getFilesDir(),"address.db"));
                byte[]buf=new byte[1024];
                int len=0;
                while((len=in.read(buf))!=-1){
                    out.write(buf,0,len);
                }
                in.close();
                out.close();
                searchAll();

            }
        });

    }

    private class MyPhoneListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state){
                case TelephonyManager.CALL_STATE_RINGING:
                    String phone=incomingNumber;
                    Log.i("Address", "---------onCallStateChanged: "+incomingNumber);
                    String address=AddressDBUtils.findaddress(getApplicationContext(),phone);
                    Toast.makeText(getApplicationContext(),address,Toast.LENGTH_LONG).show();

            }
        }
    }
}
